<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class MY_Output extends CI_Output {
	/**
	 * Constructor
	 */
	function MY_Output(){
		parent::CI_Output();
	}

	/**
	 * Envía una respuesta en formato JSON, pudiendo llamar a una función, asignarla a una variable o incluirse en un iframe
	 * @param object $var [optional]
	 * @param object $responsefunction [optional]
	 * @param object $as_script [optional]
	 * @param object $assign_variable [optional]
	 * @return void
	 */
	function set_ajax_response($var = '', $responsefunction = '', $as_script = TRUE, $assign_variable = '',$extend_var = FALSE)
	{
		//TODO: Use native json encode or native class
		if (function_exists('json_encode')){
			$json = json_encode($var);
		}else{
			include_once "Zend/Json.php";
			$json = Zend_Json::encode($var);
		}

		if ($responsefunction!=''){
			$json = $responsefunction.'('.$json.')';
		}

		if($as_script)
		{
			if(!empty($assign_variable))
			{
				if ($extend_var){
					$script = 'var '.$assign_variable.' = $.extend('.$json.','.$assign_variable.')';
				}else{
					$script = 'var '.$assign_variable.' = '.$json;
				}
			}
			else
			{
				$script = $json;
			}
		}
		else
		{
			$script= '<script language="javascript" type="text/javascript">
					window.top.window.'.$json.'
					</script>';
		}

		$this->set_output($script);
	}

	/**
	 * Devuelve una respuesta para enviar a un iframe
	 * @param object $var [optional]
	 * @param object $responsefunction [optional]
	 * @param object $cross_domain [optional]
	 * @return void
	 */
	function set_iframe_response($var = '', $responsefunction = 'iframe_response', $cross_domain = FALSE){

		$this->set_ajax_response($var, $responsefunction, $cross_domain);
	}
}
/* end of file */